<?php

namespace App\Services;

use App\Models\HardwareList;
use App\Models\HardwareMoveRecord;
use Slowlyo\OwlAdmin\Services\AdminService;

/**
 * 动线记录
 *
 * @method HardwareMoveRecord getModel()
 * @method HardwareMoveRecord|\Illuminate\Database\Query\Builder query()
 */
class HardwareMoveRecordService extends AdminService
{
	protected string $modelName = HardwareMoveRecord::class;

	public function listQuery()
	{
		return $this->query()->with(['prelocation', 'afterlocation'])->orderByDesc('id');
	}

	public function getByHardwareId($hardware_id)
	{
		$query = $this->query()
			->with(['prelocation', 'afterlocation'])
			->where('hardware_id', $hardware_id);
		
		$this->sortable($query);
		
		$list = $query->paginate(request()->input('perPage', 10));
		$items = $list->items();
		$total = $list->total();

		return compact('items', 'total');
	}

	// 添加记录时 需要更新硬件表中的current_location
	public function store($data): bool
	{
		$result = parent::store($data);
		if ($result) {
			$hardware = HardwareList::find($data['hardware_id']);
			$hardware->current_location = $data['after_location'];
			$hardware->save();
		}
		return $result;
	}
}
